package thong.servlet;

import java.io.IOException;
import java.util.SortedMap;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.jstl.sql.Result;

import thong.util.JdbcUtil;

/**
 * Servlet implementation class ProductServlet
 */
@WebServlet("/Product.do")
public class ProductServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ProductServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");


        /*
         * Duy trì chuỗi tìm kiếm của câu lệnh sql trong session
         */
        HttpSession session = request.getSession();
        if(request.getParameter("btnSearch") != null){
        	session.setAttribute("search", request.getParameter("txtSearch"));
        }
        else if(session.getAttribute("search") == null){
        	session.setAttribute("search", "");
        }
        String search = (String)session.getAttribute("search");
        
       
       // String searchSql = "SELECT * FROM Customers  WHERE FullName LIKE ?";
        //Result cus = JdbcUtil.toResult(searchSql, "%" + search + "%");
        String sql;
        if(request.getParameter("cate_id") != null)
        {
        	String cateId= request.getParameter("cate_id");
	        sql = "SELECT * FROM Products WHERE CategoryId like '%"+cateId+ "%'";
	        Result pro = JdbcUtil.toResult(sql);
	        request.setAttribute("pro", pro);
        }
        else
        {
	        sql = "SELECT * FROM Products where Name like ?";
	        Result pro = JdbcUtil.toResult(sql, "%" + search + "%");
	        request.setAttribute("pro", pro);
        }
        /*
         * Chuyển tiếp sang trang Product.jsp
         */
        request.getRequestDispatcher("pages/Product.jsp").forward(request, response);
	}

}
